<template>
  <div>
    <el-card shadow="never">
      <header-title title="催缴通知汇总管理"></header-title>
    </el-card>
    <el-card shadow="never">
      <el-row>
        <el-col :span="21">
          <div>
            商户名称:
            <el-input
              v-model="searchForm.searchName"
              placeholder="请输入内容"
              size="small"
              style="margin: 0 10px 0 10px;width: 120px;"
            ></el-input>缴费类型:
            <el-select
              v-model="searchForm.payTypeId"
              @change="changePayType"
              placeholder="请选择"
              size="small"
              style="margin: 0 10px 0 10px;width: 110px;"
            >
              <el-option
                v-for="item in searchFormPayTypeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <span class="demonstration">缴费日期：</span>
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              @change="searchFormDateRangeChange"
            ></el-date-picker>
            <!-- 开始时间:<el-date-picker v-model="searchForm.startDate" type="date" @change="changeStartDate" style="width: 145px; margin: 0 10px 0 10px;" placeholder="选择开始时间"></el-date-picker>
            结束时间:<el-date-picker v-model="searchForm.endDate" type="date" @change="changeEndDate" style="width: 145px; margin: 0 10px 0 10px;" placeholder="选择结束时间"></el-date-picker>-->
            <el-button
              @click="search"
              class="button"
              size="small"
              round
              icon="el-icon-search"
              style="margin: 10px 0;"
            >查询</el-button>
          </div>
        </el-col>
        <el-col :span="3">
          <el-button
            @click="paymentNoticeSumDialog = true"
            class="button"
            size="small"
            round
            style="margin: 10px 0;"
          >新增缴费通知</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <div>
        <el-table :data="paymentNoticeSumData" v-loading="loading" style="width: 100%">
          <el-table-column prop="marketName" label="市场名称"></el-table-column>
          <el-table-column prop="payTypeName" label="缴费项目"></el-table-column>
          <el-table-column prop="content" label="消息内容"></el-table-column>
          <el-table-column prop="count" label="发送消息总数"></el-table-column>
          <el-table-column prop="successCount" label="已缴费总数"></el-table-column>
          <el-table-column fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <el-button @click="details(scope.row)" type="text" style="color:#3dc2c2;">详情</el-button>
              <el-tooltip content="点一下就直接删除了噢" placement="top">
                <el-button @click="deletePNSum(scope.row)" type="text" style="color:#f7674a;">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <div slot="empty">
            <img src="../../../assets/blank_tip_page/blank_tip_page.png" alt />
          </div>
        </el-table>
        <el-pagination
          :page-size="searchForm.perPage"
          :current-page="searchForm.page"
          :total="searchForm.total"
          @current-change="changePaymentNoticeSumPage"
          style="margin-top: 15px;"
          background
          layout="prev, pager, next"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog
      width="580px"
      title="新增缴费通知"
      :visible.sync="paymentNoticeSumDialog"
      @close="close"
      v-if="paymentNoticeSumDialog"
    >
      <div>
        <el-form :model="modal" label-width="130px" :rules="rules" ref="modal">
          <el-form-item label="缴费内容" prop="content">
            <el-input v-model="modal.content" style="width:350px"></el-input>
          </el-form-item>
          <el-form-item label="缴费时间" prop="newDataDateRange" ref="newDataDateRange">
            <el-date-picker
              v-model="newDataDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="addModalDateRangeChanged"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="账户名称" prop="marketAccountName">
            <my-select
              ref="marketAccountNameMySelect"
              url="api/v1/backend/public/account"
              @selected="mySelectedAccountName"
              style="width:350px"
            ></my-select>
          </el-form-item>
          <el-form-item label="缴费类型" prop="type">
            <el-select
              v-model="modal.payTypeId"
              @change="addChangePayType"
              placeholder="请选择"
              style="width:350px"
            >
              <el-option
                v-for="item in payClazzOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                style="width:350px"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发送消息的方式" prop="sendType">
            <el-select
              v-model="modal.sendType"
              @change="addChangeSendType"
              placeholder="请选择"
              style="width:350px"
            >
              <el-option :key="0" label="微信公众号" :value="0"></el-option>
              <el-option :key="1" label="短信" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收费方式" prop="sendRange">
            <el-radio :disabled="radioFlag" v-model="modal.sendRange" label="1">统一收费</el-radio>
            <el-radio v-model="modal.sendRange" label="0">分开收费</el-radio>
          </el-form-item>
          <el-form-item label="金额（元）" v-show="modal.sendRange==1" prop="appointMoney">
            <el-input label="缴费金额" v-model="modal.appointMoney" style="width:350px"></el-input>
          </el-form-item>
        </el-form>
        <el-row v-show="modal.sendRange==0">
          <el-col :offset="1" :span="22">
            <el-button @click="businessDialog = true" type="text" style="color:#3dc2c2;">添加商户信息列表</el-button>
            <el-table :data="businessDataList" v-loading="loading" style="width: 100%">
              <el-table-column prop="businessName" label="商户名称"></el-table-column>
              <el-table-column prop="stallName" label="摊位号"></el-table-column>
              <!-- <el-table-column prop="businessOpenId" label="微信open_id"></el-table-column> -->
              <el-table-column prop="money" label="缴费金额(元)"></el-table-column>
              <el-table-column prop="expireDate" label="到期时间" v-if="radioFlag"></el-table-column>
              <el-table-column fixed="right" label>
                <template slot-scope="scope">
                  <el-tooltip content="点一下就直接删除了噢" placement="top">
                    <el-button
                      @click.native.prevent="removeBussinessFromAddedList(scope.$index, businessDataList)"
                      type="text"
                      style="color:#f7674a;"
                    >删除</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>

      <el-dialog
        width="380px"
        title="新增商户信息"
        :visible.sync="businessDialog"
        append-to-body
        @close="addBusinessDialogclose"
      >
        <div>
          <el-form :model="businessModal" label-width="100px">
            <el-form-item label="商户名称" prop="businessName">
              <my-select ref="businessMySelect" url="api/v1/backend/public/business/stall" @selected='mySelectedBusiness' style="width:220px"></my-select>
            </el-form-item>
            <el-form-item label="缴费金额(元)" prop="money">
              <el-input v-model="businessModal.money" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item v-show="radioFlag" label="到期时间" prop="expireDate">
              <el-date-picker
                v-model="businessModal.expireDate"
                align="right"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click.stop="submitBusiness">提交新增商户信息</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.stop="submit('modal')">提交新增缴费通知</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HeaderTitle from "@/components/HeaderTitle";
import MySelect from "@/components/MySelect";
import { formatDate2 } from "@/utils";
export default {
  name: "PaymentNoticeSum",
  components: {
    HeaderTitle,
    MySelect
  },
  data() {
    let newDataDateRange = (rule, value, callback) => {
      if (this.newDataDateRange == "") {
        callback(new Error("请选择缴费时间"));
      } else {
        callback();
      }
    };
    let type = (rule, value, callback) => {
      if (this.modal.payTypeId == null) {
        callback(new Error("请选择缴费类型"));
      } else {
        callback();
      }
    };
    let sendType = (rule, value, callback) => {
      if (this.modal.sendType == null) {
        callback(new Error("请选择发送信息的方式"));
      } else {
        callback();
      }
    };
    return {
      searchForm: {
        searchName: "",
        payTypeId: -1,
        dateRange: [],
        startDate: "",
        endDate: "",
        perPage: 10, // 每页显示10条
        page: 1, // 当前页
        total: 0
      },
      radioFlag: false,
      loading: true,
      paymentNoticeSumData: [],
      paymentNoticeSumDialog: false,
      modal: { sendRange: "1" },
      businessDataList: [],
      businessDialog: false,
      businessModal: {},
      newModal: {},
      newDataDateRange: [],
      payClazzOptions: [],
      searchFormPayTypeOptions: [],
      sendRange: "1",
      rules: {
        content: [
          { required: true, message: "请输入缴费内容", trigger: "blur" }
        ],
        newDataDateRange: [
          {
            required: true,
            validator: newDataDateRange,
            trigger: ["change"]
          }
        ],
        marketAccountName: [
          { required: true, message: "请输入账户名称", trigger: "change" }
        ],
        type: [
          {
            required: true,
            validator: type,
            trigger: ["change"]
          }
        ],
        sendType: [
          {
            required: true,
            validator: sendType,
            trigger: ["change"]
          }
        ],
        sendRange: [
          {
            required: true,
            message: "请选择收费方式", trigger: "change"
          }
        ],
        appointMoney: [
          { required: true, message: "请输入金额", trigger: "change" }
        ]
      }
    };
  },
  watch: {
    "$store.state.app.marketId"(val, oldVal) {
      this.getPaymentNoticeSumList(this.searchForm);
    }
  },
  mounted() {
    this.initSelect();
    this.getPaymentNoticeSumList(this.searchForm);
  },
  methods:{
    initSelect(){
      this.$store.dispatch("payment/fetchPayClazz").then(responseData => {
          this.payClazzOptions = responseData.data
          this.searchFormPayTypeOptions = responseData.data
          this.searchFormPayTypeOptions.unshift({id:-1, name:'全部'})
        }).catch(err => {
          console.log(err)
        })
    },
    // 缴费类型
    changePayType(val) {
      this.searchForm.payTypeId = val;
    },

    searchFormDateRangeChange(dateRange) {
      this.searchForm.startDate = formatDate2(dateRange[0]);
      this.searchForm.endDate = formatDate2(dateRange[1]);
    },
    // 获取缴费通知汇总列表
    getPaymentNoticeSumList(searchForm) {
      console.log("searchForm", searchForm);
      this.$store
        .dispatch("payment/fetchPaymentNoticeSumData", searchForm)
        .then(data => {
          this.loading = false;
          this.paymentNoticeSumData = data.items;
          this.searchForm.total = data.total;
        })
        .catch(err => {
          this.loading = false;
          this.paymentNoticeSumData = [];
          this.searchForm.total = 0;
        });
    },
    search() {
      this.searchForm.page = 1;
      this.getPaymentNoticeSumList(this.searchForm);
    },
    changePaymentNoticeSumPage(num) {
      this.searchForm.page = num;
      this.getPaymentNoticeSumList(this.searchForm);
    },
    addModalDateRangeChanged(dateRange) {
      this.modal.startDate = formatDate2(dateRange[0]);
      this.modal.endDate = formatDate2(dateRange[1]);
    },
    mySelectedAccountName(obj) {
      this.modal.marketAccountId = obj.value;
      this.modal.marketAccountName = obj.label;
    },
    addChangePayType(val) {
      this.modal.payTypeId = val;
      this.radioFlag = false;
      console.log("id", val);
      console.log("options", this.payClazzOptions);
      for (var option of this.payClazzOptions) {
        if (val == option.id && option.name == "租金") {
          this.radioFlag = true;
        }
      }
    },
    addChangeSendType(val) {
      this.modal.sendType = val;
    },
    mySelectedBusiness(obj){
      console.log(obj)
      this.businessModal.businessId = obj.exData.businessId
      this.businessModal.businessName = obj.exData.businessName
      this.businessModal.stallName = obj.stallName
      this.businessModal.personInCharge = obj.exData.personInCharge
      this.businessModal.phone = obj.exData.phone
      this.businessModal.businessOpenId = obj.businessOpenId
      console.log('bussinessModal', this.businessModal)
    },
    // 提交多选商户信息
    submitBusiness() {
      this.businessDialog = false;
      this.businessDataList.push(this.businessModal);
    },
    // 提交新增缴费通知
    submit(formName) {
      this.newModal = this.modal;
      this.$refs[formName].validate(valid => {
        if (valid) {
          for (var businessData of this.businessDataList) {
            businessData.money = businessData.money * 100;
          }

          console.log("businessDataList", this.businessDataList);

          this.newModal = Object.assign(
            { businessDataList: JSON.stringify(this.businessDataList) },
            this.newModal
          );
          if (
            this.newModal.appointMoney == null ||
            this.newModal.appointMoney == ""
          ) {
            this.newModal.appointMoney = 0;
          }

          this.newModal.appointMoney = this.newModal.appointMoney * 100;
          this.paymentNoticeSumDialog = false;
          this.$store
            .dispatch("payment/fetchSubmitPaymentNoticeSum", this.newModal)
            .then(data => {
              if (data) {
                this.$message({
                  type: "success",
                  message: "添加成功,请刷新!"
                });
              }
              this.close();
              this.modal = {};
              this.businessModal = {};
              this.businessDataList = [];
              this.getPaymentNoticeSumList(this.searchForm);
            })
            .catch(err => {
              this.$message({
                type: "error",
                message: "添加失败，请刷新!"
              });
            });
        } else {
          this.$message.error("表单验证未通过");
          return false;
        }
      });
    },
    close() {
      // 清空

      this.businessDataList = []
      this.modal = {}
      this.newModal = {}
    },
    addBusinessDialogclose() {
      this.$refs["businessMySelect"].clear();
      this.businessModal = {};
    },
    // 缴费通知详情
    details(row) {
      const businessPayTheFeesMessageId = row.businessPayTheFeesMessageId;
      this.$router.push({
        path: `paymentNoticeSum/paymentNotice/${businessPayTheFeesMessageId}`,
        query: {
          paymentNoticeSumDetails: row
        }
      });
    },
    // 删除缴费通知汇总
    deletePNSum(row) {
      const businessPayTheFeesMessageId = row.businessPayTheFeesMessageId;
      this.$store
        .dispatch("payment/fetchDeletePNSum", { businessPayTheFeesMessageId })
        .then(data => {
          if (data) {
            this.$message({
              type: "success",
              message: "删除成功，请刷新页面！"
            });
          }
          this.getPaymentNoticeSumList(this.searchForm);
        });
    },

    removeBussinessFromAddedList(index, rows) {
      console.log("rows", rows);
      rows.splice(index, 1);
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-table__empty-text {
  width: 100%;
}
.button {
  background: #64d9d6;
  color: #fff;
  margin-left: 40px;
}
// /deep/ .el-dialog {
//   width: 520px
// }
</style>
